//Some functions
function puts(str){
    console.log(str);
}

Number.prototype.times = function(iterator){
    for(var i=0; i<this; i++){
        iterator(i);
    }
}

Array.prototype.each = function(iterator){
    for(var i=0; i<this.length; i++){
        iterator(this[i], i);
    }
}

//Now it starts
function closures_in_loop_block(nclosures){
    var closures = [];
    (nclosures || 5).times(function(i){
        closures.push(function(){return "Actual: i = "+i;});
    });
    return closures;
}

function closures_in_loop(nclosures){
    var closures = [];
    for(var i=0; i<(nclosures || 5); i++){
        closures.push(function(){return "Actual: i = "+i;});
    }
    return closures;
}

function closures_var_after(){
    var closures = [];
    var i = 0;
    closures.push(function(){return "Actual: i = "+i});
    i = 1;
    closures.push(function(){i = 2; return "Actual: i = "+i});
    i = 3;
    closures.push(function(){return "Actual: i = "+i});
    return closures;
}

function debug_closures(closures, title){
    puts(title || "");
    closures.each(function(cl, i){puts("Closure "+i+": "+cl());});
    puts("\n\n");
}

debug_closures(closures_in_loop_block(), "Closures in a loop iterated by passing it\n a code block")
debug_closures(closures_in_loop(), "Closures in a while statement")
debug_closures(closures_var_after(), "Closures with variable defining")